<template>
  <el-upload
    class="upload-demo"
    :action="host"
    :before-upload="beforeUpload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :file-list="fileList"
    :data="objectData"
    list-type="picture">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
</template>
<script>
import {uploadFileOSS} from "@/api/file/file";
import {getTime} from "@/utils";

export default {
  data() {
    return {
      fileList: [],
      //服务端签名信息
      // signatureOSS: new FormData(),
      objectData: {},
      //服务端地址
      host: '',
      moderValue:""
    };
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList; // 同步更新fileList
    },
    handlePreview(file) {
      console.log(file);
    },
    /**
     * 获取服务端签名
     * @param file
     */
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // 每次上传都创建新的FormData，避免缓存
        const signatureOSS = new FormData();
        uploadFileOSS().then(response => {
          console.log(response.data, "data")
          this.host = response.data.host
          console.log(this.host, "host")
          signatureOSS.append("success_action_status", "200");
          signatureOSS.append("policy", response.data.policy);
          signatureOSS.append("x-oss-signature", response.data.signature);
          signatureOSS.append("x-oss-signature-version", "OSS4-HMAC-SHA256");
          signatureOSS.append("x-oss-credential", response.data.x_oss_credential);
          signatureOSS.append("x-oss-date", response.data.x_oss_date);
          signatureOSS.append("key", response.data.dir +getTime().getTime()+ file.name); // 文件名
          signatureOSS.append("x-oss-security-token", response.data.security_token);
          // this.signatureOSS.append("file", file); // file 必须为最后一个表单域
          this.objectData = Object.fromEntries(signatureOSS.entries())
          console.log(this.objectData, "signatureOSS")
          resolve(true)
        }).catch(function (error) {
          console.log(error)
          reject(false)
        })
      })
    },
    handleSuccess(response, file) {
      // 上传成功后，拼接完整 OSS URL
      const url = `${this.host}/${this.objectData.key}`;
      console.log(url,"url")
      // 通过 v-model 更新父组件的值
      this.emitInput(url);
      // this.moderValue=''
      // this.signatureOSS= new FormData()
      // 重置表单数据和文件列表，避免缓存
      this.objectData = {};
      this.fileList = []; // 清空文件列表
      this.moderValue = '';
    }
  }
}
</script>
